﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Drawing;

namespace Light.Utility
{
    // 应用程序配置类...
    public class ApplicationSetting
    {
        private static string configurationFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

        // 构造...
        static ApplicationSetting()
        {
        }

        #region 属性...

        //...
        public static string ConfigurationFileName
        {
            get
            {
                return configurationFileName;
            }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    configurationFileName = value;
                }
            }
        }

        public static string ConnectionString
        {
            get
            {
                ConnectionStringSettings settings = GetConnectionStringSettings(ReadAppSetting("defaultConnectionStringName", "default"));
                if (settings != null)
                {
                    return settings.ConnectionString;
                }
                else
                {
                    return null;
                }
            }
        }

        public static string ProviderName
        {
            get
            {
                ConnectionStringSettings settings = GetConnectionStringSettings(ReadAppSetting("defaultConnectionStringName", "default"));
                if (settings != null && !String.IsNullOrWhiteSpace(settings.ProviderName))
                {
                    return settings.ProviderName;
                }
                else
                {
                    //return null;
                    return "System.Data.SqlClient";//未指定时，默认为SqServer
                }
            }
        }

        public static string FriendlyName
        {
            get
            {
                return ReadAppSetting("friendlyName", String.Empty);
            }
        }

        #endregion 属性...

        #region 读配置...

        //...
        public static int ReadAppSetting(string key, int defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToInt32(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        //...
        public static double ReadAppSetting(string key, double defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToDouble(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        // ...
        public static float ReadAppSetting(string key, float defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToSingle(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        // ...
        public static decimal ReadAppSetting(string key, decimal defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToDecimal(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        // ...
        public static DateTime ReadAppSetting(string key, DateTime defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            try
            {
                return (String.IsNullOrEmpty(setting)) ? defaultValue : Convert.ToDateTime(setting);
            }
            catch
            {
                return defaultValue;
            }
        }

        //...
        public static string ReadAppSetting(string key, string defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            return (String.IsNullOrEmpty(setting)) ? defaultValue : setting;
        }

        //...
        public static bool ReadAppSetting(string key, bool defaultValue)
        {
            Configuration configuration = OpenConfiguration();
            string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

            return (String.IsNullOrEmpty(setting)) ? defaultValue : (string.Compare(setting, Boolean.TrueString, true) == 0);
        }

        ////...
        //public static Color ReadAppSetting(string key, Color defaultValue)
        //{
        //    Configuration configuration = OpenConfiguration();
        //    string setting = (configuration.AppSettings.Settings[key] != null ? configuration.AppSettings.Settings[key].Value : null);

        //    Color color = Color.Empty;
        //    if (!string.IsNullOrEmpty(setting))
        //    {
        //        try
        //        {
        //            if (setting.StartsWith("#") && setting.Length > 3) /// #AAA || #AAAAAA
        //            {
        //                setting = setting.Substring(1);
        //                if (setting.Length == 3)
        //                {
        //                    color = Color.FromArgb(Int32.Parse(string.Format("{0}{1}", setting[0], setting[0]), System.Globalization.NumberStyles.AllowHexSpecifier),
        //                                           Int32.Parse(string.Format("{0}{1}", setting[1], setting[1]), System.Globalization.NumberStyles.AllowHexSpecifier),
        //                                           Int32.Parse(string.Format("{0}{1}", setting[2], setting[2]), System.Globalization.NumberStyles.AllowHexSpecifier));
        //                }
        //                else if (setting.Length == 6)
        //                {
        //                    color = Color.FromArgb(Int32.Parse(setting.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier),
        //                                           Int32.Parse(setting.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier),
        //                                           Int32.Parse(setting.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier));
        //                }
        //            }
        //            else if (StringHelper.IsNumeric(setting))
        //            {
        //                color = Color.FromArgb(int.Parse(setting));
        //            }
        //            else if (setting.Split(',', ' ').Length == 3)
        //            {
        //                string[] list = setting.Split(',', ' ');
        //                color = Color.FromArgb(int.Parse(list[0]), int.Parse(list[1]), int.Parse(list[2]));
        //            }
        //            else
        //            {
        //                color = Color.FromName(setting);
        //            }
        //        }
        //        catch
        //        {
        //            color = defaultValue;
        //        }

        //        return color;
        //    }

        //    return color;
        //}

        #endregion 读配置...

        #region 写配置
        public static void WriteAppSetting(string key, object value)
        {
            Configuration configuration = OpenConfiguration();

            AppSettingsSection appSection = configuration.AppSettings;
            if (value == null)
                appSection.Settings.Remove(key);
            else
            {
                if (appSection.Settings[key] != null)
                    appSection.Settings[key].Value = (value.ToString());
                else
                    appSection.Settings.Add(key, value.ToString());
            }

            appSection.SectionInformation.ForceSave = true;
            configuration.Save();
        }
        #endregion

        #region Public
        public static ConnectionStringSettings GetConnectionStringSettings(string name)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            Configuration configuration = OpenConfiguration();
            return configuration.ConnectionStrings.ConnectionStrings[name];
        }

        public static string[] GetConnectionStringNames()
        {
            return GetConnectionStringNames(true);
        }

        public static string[] GetConnectionStringNames(bool all)
        {
            string defName = ReadAppSetting("defaultConnectionStringName", "default");

            Configuration configuration = OpenConfiguration();
            ConnectionStringSettingsCollection cssc = configuration.ConnectionStrings.ConnectionStrings;

            List<string> list = new List<string>();

            for (int i = 0; i < cssc.Count; i++)
            {
                if (all || String.Compare(cssc[i].Name, defName, true) != 0)
                    list.Add(cssc[i].Name);
            }

            return list.ToArray();
        }
        #endregion

        #region Protected
        protected static Configuration OpenConfiguration()
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = configurationFileName;

            return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        }
        #endregion
    }
}